package com.atguigu.order.service.impl;

import com.atguigu.order.client.CourseClient;
import com.atguigu.order.client.UcenterClient;
import com.atguigu.order.entity.TOrder;
import com.atguigu.order.entity.vo.CourseOrderVo;
import com.atguigu.order.entity.vo.MemberOrderVo;
import com.atguigu.order.mapper.TOrderMapper;
import com.atguigu.order.service.TOrderService;
import com.atguigu.serviceBash.GlobalException;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;

/**
 * <p>
 * 订单 服务实现类
 * </p>
 *
 * @author admin
 * @since 2020-07-16
 */
@Service
@Transactional(isolation = Isolation.SERIALIZABLE, propagation = Propagation.REQUIRED)
public class TOrderServiceImpl extends ServiceImpl<TOrderMapper, TOrder> implements TOrderService {

    @Autowired
    private CourseClient courseClient;
    @Autowired
    private UcenterClient ucenterClient;

    @Override
    public String createOrder(String courseId, String id) {
//feign 远程 ucenterClient接口
        MemberOrderVo memberOrderVo = ucenterClient.getMemb(id);
        if (memberOrderVo == null) {
            throw new GlobalException("用户未登录", 20001);
        }
//feign 远程 courseWebVoClient接口
        CourseOrderVo courseOrderVo = courseClient.getCourseOrderInfo(courseId);
        if (courseOrderVo != null) {
//          取课程信息
            TOrder tOrder = new TOrder();
            tOrder.setCourseId(courseOrderVo.getId());
            tOrder.setCourseTitle(courseOrderVo.getTitle());
            tOrder.setCourseCover(courseOrderVo.getCover());
            tOrder.setTeacherName(courseOrderVo.getTeacherName());
//            价钱 价钱 价钱
            tOrder.setTotalFee(courseOrderVo.getPrice());
//            取用户信息
            tOrder.setMemberId(memberOrderVo.getMemberId());
//            微信登录用户手机号为空
            tOrder.setMobile(memberOrderVo.getMobile());
            tOrder.setNickname(memberOrderVo.getNickname());

//            1微信 2支付宝
            tOrder.setPayType(1);
//            默认未支付状态
            tOrder.setStatus(0);
//            生成订单号
            UUID uuid = UUID.randomUUID();
            tOrder.setOrderNo(uuid.toString().replace("-", ""));
            uuid = null;
            try {
                int count = baseMapper.insert(tOrder);
                if (count > 0) {
                    return tOrder.getId();
                } else {
                    throw new GlobalException("错误", 20001);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return null;
    }


}
